<?php

namespace App\Http\Controllers;

use App\Models\AdminRolesModel;
use Illuminate\Http\Request;
use App\Models\AdminUsersModel;
use Illuminate\Support\Facades\Validator;

class UserController extends BaseController
{

    protected $rule = [
        'loginname' => 'required|regex:/^[a-zA-Z][a-zA-Z0-9_]{3,20}$/',
        'realname' => 'required',
        'phone' => 'required|regex:/^1[34578]\d{9}$/',
        'email' => 'required|email',
        'roles' => 'required'
    ];
    protected $message = [];

    public function __construct()
    {
        $this->message = [
            'loginname.required' => trans("user.loginname_required"),
            'loginname.regex' => trans("user.loginname_regex"),
            'realname.required' => trans("user.realname_required"),
            'phone.required' => trans("user.phone_required"),
            'phone.regex' => trans("user.phone_regex"),
            'email.required' => trans("user.email_required"),
            'email.email' => trans("user.email_email"),
            'roles.required' => trans("user.roles_required"),
        ];
    }

    /**
     * 管理员列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $loginname = $request->input('loginname', '');
        $realname = $request->input('realname', '');
        $phone = $request->input('phone', '');
        $email = $request->input('email', '');
        $arr = [
            'loginname' => $loginname,
            'realname' => $realname,
            'phone' => $phone,
            'email' => $email
        ];
        $users = AdminUsersModel::getAdminUsersList($arr);
        return view('user.index', [
            'users' => $users,
            'params' => $arr,
        ]);
    }

    /**
     * 删除和批量删除管理员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request)
    {
        if (!$request->ajax()) {
            return $this->_failed(trans('common.illegal_request'));
        }
        $id = strval($request->input('id'));
        if (strpos($id, ",") !== false) {
            $id = array_filter(explode(",", $id));
        } else {
            $id = array($id);
        }
        if (empty($id)) {
            return $this->_failed(trans('user.user_not_existed'));
        }
        $delIds = [];
        $users = AdminUsersModel::getAllAdminUsers(['id' => $id]);
        foreach ($users as $key => $user) {
            if ($user->roles == AdminUsersModel::SUPERUSERS) {
                unset($users[$key]);
                continue;
            }
            $delIds[] = $user->id;
        }
        if (empty($delIds)) {
            return $this->_failed(trans('user.user_not_existed'));
        }
        if (!AdminUsersModel::deleteAdminUsers(['id' => $delIds])) {
            return $this->_failed(trans('common.del_failed'));
        }
        return $this->_success();
    }

    /**
     * 禁用和启用管理员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function disable(Request $request)
    {
        if (!$request->ajax()) {
            return $this->_failed(trans('common.illegal_request'));
        }
        $id = strval($request->input('id'));
        $user = AdminUsersModel::getAdminUsersData(['id' => $id]);
        if (empty($user)) {
            return $this->_failed(trans('user.user_not_existed'));
        }
        if ($user->roles == AdminUsersModel::SUPERUSERS) {
            return $this->_failed(trans('user.not_disable_superuser'));
        }
        $status = AdminUsersModel::USERSENABLE;
        if ($user->status == AdminUsersModel::USERSENABLE) {
            $status = AdminUsersModel::USERSDISABLE;
        }
        if (!AdminUsersModel::updateAdminUsers(['id' => $id], ['status' => $status])) {
            return $this->_failed(trans('common.update_failed'));
        }
        return $this->_success();
    }

    /**
     * 展示新增和修改管理员界面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(Request $request)
    {
        $roles = AdminRolesModel::getAllAdminRoles();
        if ($request->has('id')) {
            $id = intval($request->input('id'));
            $user = AdminUsersModel::getAdminUsersData(['id' => $id]);
            return view('user.show', [
                'user' => $user,
                'roles' => $roles
            ]);
        }
        return view('user.show', [
            'roles' => $roles
        ]);
    }

    /**
     * 新增管理员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        $data = $request->input();
        $validator = Validator::make($data, $this->rule, $this->message);
        if (!$validator->passes()) {
            return $this->_failed($validator->errors()->first());
        }
        if (AdminUsersModel::getAdminUsersExists(['loginname' => $data['loginname']])) {
            return $this->_failed(trans('user.loginname_repeat'));
        }
        if (AdminUsersModel::getAdminUsersExists(['realname' => $data['realname']])) {
            return $this->_failed(trans('user.realname_repeat'));
        }
        if (AdminUsersModel::getAdminUsersExists(['phone' => $data['phone']])) {
            return $this->_failed(trans('user.phone_repeat'));
        }
        if (AdminUsersModel::getAdminUsersExists(['email' => $data['email']])) {
            return $this->_failed(trans('user.email_repeat'));
        }
        $data['salt'] = AdminUsersModel::getSalt();
        $data['password'] = sha1(config('app.default_password') . $data['salt']);
        if (!AdminUsersModel::insertAdminUsers($data)) {
            return $this->_failed(trans('common.insert_failed'));
        }
        return $this->_success();
    }

    /**
     * 编辑管理员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        $data = $request->input();
        $validator = Validator::make($data, $this->rule, $this->message);
        if (!$validator->passes()) {
            return $this->_failed($validator->errors()->first());
        }
        $user = AdminUsersModel::getAdminUsersData(['id' => $data['id']]);
        if ($user->loginname != $data['loginname']) {
            if (AdminUsersModel::getAdminUsersExists(['loginname' => $data['loginname']])) {
                return $this->_failed(trans('user.loginname_repeat'));
            }
        }
        if ($user->realname != $data['realname']) {
            if (AdminUsersModel::getAdminUsersExists(['realname' => $data['realname']])) {
                return $this->_failed(trans('user.realname_repeat'));
            }
        }
        if ($user->phone != $data['phone']) {
            if (AdminUsersModel::getAdminUsersExists(['phone' => $data['phone']])) {
                return $this->_failed(trans('user.phone_repeat'));
            }
        }
        if ($user->email != $data['email']) {
            if (AdminUsersModel::getAdminUsersExists(['email' => $data['email']])) {
                return $this->_failed(trans('user.email_repeat'));
            }
        }
        $update = [
            'loginname' => $data['loginname'],
            'realname' => $data['realname'],
            'phone' => $data['phone'],
            'email' => $data['email'],
            'roles' => $data['roles'],
            'update_time' => time()
        ];
        if (!AdminUsersModel::updateAdminUsers(['id' => $data['id']], $update)) {
            return $this->_failed(trans('common.update_failed'));
        }
        return $this->_success();
    }


    public function modpass()
    {
        return view('user/modpass');
    }

    public function domodpass(Request $request)
    {
        if (!$request->ajax()) {
            return $this->_failed(trans('common.illegal_request'));
        }
        $data = $request->input();
        $validator = Validator::make($data, [
            'id' => 'required',
            'oldpassword' => 'required',
            'password' => 'required',
            'repassword' => 'required',
        ], [
            'id.required' => trans('user.user_not_existed'),
            'oldpassword.required' => trans('user.oldpassword_empty'),
            'password.required' => trans('user.password_empty'),
            'repassword.required' => trans('user.repassword_empty'),
        ]);
        if (!$validator->passes()) {
            return $this->_failed($validator->errors()->first());
        }
        if ($data['password'] !== $data['repassword']) {
            return $this->_failed(trans('user.repassword_equal_password'));
        }
        $user = AdminUsersModel::getAdminUsersData(['id' => $data['id']]);
        if (is_null($user)) {
            return $this->_failed(trans('user.user_not_existed'));
        }
        if ($user->password != sha1($data['oldpassword'] . $user->salt)) {
            return $this->_failed(trans('login.password_error'));
        }
        $update = [
            'password' => sha1($data['password'] . $user->salt),
            'update_time' => time()
        ];
        if (!AdminUsersModel::updateAdminUsers(['id' => $data['id']], $update)) {
            return $this->_failed(trans('user.modify_password_failed'));
        }
        return $this->_success();
    }
}
